<template>
    <div>
        <el-row>
            <!-- 信息查询 -->
            <el-form size="mini" inline ref="queryFormRef" :model="queryForm">
                <el-form-item label="车牌号" prop="carNumber">
                    <el-input v-model="queryForm.carNumber"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleQuery">查询</el-button>
                    <el-button @click="resetForm('queryForm'), getListCar()">重置</el-button>
                    <el-button type="primary" plain @click="handleAdd">添加</el-button>
                </el-form-item>
            </el-form>

            <!-- 表格 -->
            <el-table :data="carList">
                <el-table-column type="index" label="序号" align="center" width="50"
                    show-overflow-tooltip></el-table-column>
                <el-table-column prop="carNumber" label="车牌号" align="center" show-overflow-tooltip>
                </el-table-column>
                <el-table-column prop="name" label="人员姓名" align="center" width="250"
                    show-overflow-tooltip></el-table-column>
                <el-table-column prop="phoneNumber" label="手机号码" align="center" width="250"
                    show-overflow-tooltip></el-table-column>
                <el-table-column prop="createTime" label="创建时间" align="center" width="200"
                    show-overflow-tooltip></el-table-column>
                <el-table-column label="操作" align="center" width="280" show-overflow-tooltip>
                    <template #default="{ row }">
                        <el-button type="primary" @click="handleEdit(row)">编辑</el-button>
                        <el-button type="danger" @click="handleDetele(row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页组件 -->
            <el-row type="flex">
                <div class="block">
                    <!-- .sync类似v-model，实现页面数据双向响应式 -->
                    <el-pagination background :current-page.sync="pageIniation.pageNum" :page-sizes="[5, 10, 15, 20]"
                        :page-size="pageIniation.pageSize" layout="total, sizes, prev, pager, next, jumper"
                        :total="pageIniation.total" @current-change="handleChange">
                    </el-pagination>
                </div>
            </el-row>

            <!-- 弹窗：实现添加和编辑功能 -->
            <el-dialog :visible.sync="dialog.visible" width="400px" @close="resetForm('dialogForm')">
                <template #title>
                    <div style="text-align: center;">
                        {{ dialog.mode === "add" ? "添加车辆" : "编辑车辆" }}
                    </div>
                </template>
                <el-form :model="dialog.form" label-width="100px" label-position="left" size="small"
                    :rules="dialog.rules" ref="dialogFormRef" hide-required-asterisk>
                    <el-form-item label="车牌号" prop="carNumber">
                        <el-input v-model="dialog.form.carNumber">
                        </el-input>
                    </el-form-item>
                    <el-form-item label="车主人" prop="personId">
                        <el-button type="text" @click=personDialog v-model="dialog.form.personId">{{ carPersonName
                        }}</el-button>
                    </el-form-item>

                    <el-form-item align="right">
                        <el-button type="plain" @click="dialog.visible = false, resetForm('dialogForm')">取消</el-button>
                        <el-button type="primary" @click="handleSubmit">确定</el-button>
                    </el-form-item>
                </el-form>
            </el-dialog>

            <!-- 选择人员的弹窗组件 -->
            <car-person :visible.sync="personDialogVisible" :choose-person="choosePersonData"
                @choose="handlePerson"></car-person>
        </el-row>
    </div>
</template>

<script>
import CarPerson from '@/components/CarPerson.vue';
import { query } from '@/utils/common.js';
import { listCar, addCar, editCar, deleteCar } from '@/api/cars.js';
export default {
    name: "Cars",
    data() {
        return {
            //小区id对应下的车辆信息
            plotId: undefined,

            //车辆列表
            carList: [
            ],
            queryForm: {
                carNumber: undefined,
            },

            //分页
            pageIniation: {
                pageNum: 1,
                pageSize: 5,
                total: 0,
            },

            //添加的弹窗
            dialog: {
                mode: "add",
                visible: false,
                form: {
                    carNumber: undefined,
                    personId: undefined
                },
                //校验
                rules: {
                    carNumber: [{ required: true, message: "请输入车牌号", trigger: "blur" }],
                }

            },

            //显示选择车主人的弹窗
            personDialogVisible: false,

            //车主人名字
            carPersonName: "请选择",
            choosePersonData: undefined,

        }
    },

    components: {
        CarPerson,
    },
    computed: {

    },

    created() {
        //小区id对应下的车辆信息
        this.plotId = this.$store.state.curId,
        this.getListCar()
    },

    methods: {
        //获取车辆列表
        getListCar(query = {}) {
            const { total, ...rest } = this.pageIniation
            listCar({ ...query, ...rest, plotId: this.plotId }).then(res => {
                this.carList = res.rows
                this.pageIniation.total = res.total
            })

        },

        //查询
        handleQuery() {
            //查询为空(包括空格)时，进行提示，提示先输入值，至少有一个输入框有值：some,用于数组
            const hasInput = query(this.queryForm)

            this.pageIniation.pageNum = 1

            if (hasInput) return this.getListCar(this.queryForm)
            this.$message.warning("请输入值！")
        },

        //查询后重置
        resetForm(refName) {
            this.$refs[`${refName}Ref`].resetFields()
        },

        handleChange(value) {
            //更新当前页
            this.pageIniation.pageNum = value
            this.getListCar(this.queryForm)
        },

        handleChangeSize(value) {
            //更新当前页
            this.pageIniation.pageSize = value
            this.getListCar(this.queryForm)
        },

        //添加
        handleAdd() {
            this.dialog.visible = true
            this.dialog.mode = "add"

            /* 实现点击编辑之后再点添加时数据清空 */
            // 重置表单数据（清空车牌号和人员ID）
            this.dialog.form = {
                carNumber: undefined,
                personId: undefined
            };
            // 重置车主人显示名称
            this.carPersonName = "请选择";
            // 重置选择人员的关联数据
            this.choosePersonData = undefined
        },

        //选择车主人打开弹窗
        personDialog() {
            this.personDialogVisible = true
        },

        //获取选择人员
        handlePerson(person) {
            this.dialog.form.personId = person.personId
            this.carPersonName = person.name
        },

        //编辑
        handleEdit(row) {

            this.dialog.visible = true
            this.dialog.mode = "edit"
            //数据回显
            this.choosePersonData = row.name
            this.carPersonName = row.name
            this.$nextTick(() => {
                this.dialog.form = JSON.parse(JSON.stringify(row))
            })
        },

        //提交
        handleSubmit() {
            //空值提交先进行校验提醒
            this.$refs[`dialogFormRef`].validate(async valid => {

                //检验失败
                if (!valid) return
                //校验成功(判断是添加还是编辑)
                //过滤不需要的参数
                let { createTime, carId, ...rest } = this.dialog.form
                let result = {}
                switch (this.dialog.mode) {
                    case "add":
                        try {
                            result = await addCar({ ...rest, carId, plotId: this.plotId })
                        } catch (error) {
                            break;
                        }

                    case "edit":
                        try {
                            result = await editCar({ ...rest, carId, plotId: this.plotId })
                        } catch (error) {
                            break
                        }
                }

                this.$message.success(result.msg)
                this.getListCar()
                //关闭弹窗
                this.dialog.visible = false
                //添加后重置表单
                this.resetForm("dialogForm")//this.resetForm(dialog.Form)
            })

        },

        //删除停车场
        handleDetele(row) {
            //提示
            this.$confirm(`是否删除【${row.name}】？`, "系统提示", {
                type: "warning",
                //确定.then
            }).then(() => {
                deleteCar(row.carId).then(res => {
                    this.$message.success(res.msg)
                    //删除后，重新更新车辆信息
                    this.getListCar()
                })
                //取消.catch
            }).catch((err) => { })
        }

    }
}

</script>

<style lang="scss" scoped></style>